package cn.com.xjnt.vas.web.manage.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.frameworks.core.logger.annotation.RunLogger;
import com.frameworks.core.web.controller.BaseController;
import com.frameworks.core.web.page.WebPage;
import com.frameworks.core.web.result.DataResult;
import com.frameworks.core.web.result.MsgResult;
import com.frameworks.core.web.search.DynamicSpecifications;
import com.google.common.collect.Lists;

import cn.com.xjnt.vas.manage.domain.entity.Account;
import cn.com.xjnt.vas.manage.domain.vo.AccountVo;
import cn.com.xjnt.vas.manage.service.AccountService;

@Controller
@RequestMapping("/manage/account")
public class AccountController extends BaseController {
	
	private static final String VIEW_PAGE = "manage/account/view";
	private static final String FORM_PAGE = "manage/account/form";
	private static final String FORM_PWD_PAGE = "manage/account/pwd";
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private Mapper mapper;
		
	protected AccountService getService() {
		return accountService;
	}
	
	@RequiresPermissions(value={"Account:show"})
	@RequestMapping(value="", method={RequestMethod.GET})
	public ModelAndView show(HttpServletRequest request){
		return new ModelAndView(VIEW_PAGE);
	}
	
	@RequiresPermissions(value={"Account:show"})
	@RequestMapping(value="/list", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public DataResult list(HttpServletRequest request, WebPage webPage){
		DataResult dataRet = new DataResult();
		try{
			Specification<Account> specification = DynamicSpecifications.bySearchFilter(request, Account.class);
			List<Account> accounts = getService().findByCondition(specification, webPage);
			List<AccountVo> lstVo = Lists.newArrayList();
			for (Account account : accounts) {
				AccountVo vo = mapper.map(account, AccountVo.class);
				lstVo.add(vo);
			}
			dataRet.pushOk("获取数据列表成功！");
			dataRet.setTotal(webPage.getTotalCount());
			dataRet.setRows(lstVo);
		} catch (Exception e){
			dataRet.pushError("获取数据列表失败！");
			logger.error("获取数据列表异常！", e);
		}
		return dataRet;
	}
	
	@RequiresPermissions(value={"Account:show"})
	@RequestMapping(value="/add", method={RequestMethod.GET})
	public ModelAndView add(HttpServletRequest request){
		return new ModelAndView(FORM_PAGE);
	}

	@RunLogger(value="添加用户账号", isSaveRequest=true)
	@RequiresPermissions(value={"Account:add"})
	@RequestMapping(value="/add", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public MsgResult store(Account entity){
		MsgResult msgRet = new MsgResult();
		try {
			getService().save(entity);
			msgRet.pushOk("添加成功！");
		} catch(Exception e) {
			msgRet.pushError("添加失败：" + e.getMessage());
			logger.error("添加时，发生异常！", e);
		}
		return msgRet;
	}
	
	@RequiresPermissions(value={"Account:show"})
	@RequestMapping(value="/edit/{id}", method={RequestMethod.GET})
	public ModelAndView edit(@PathVariable("id") Long id){
		ModelAndView mav = new ModelAndView(FORM_PAGE);
		Account account = getService().findById(id);
		mav.addObject("account", account);
		return mav;
	}

	@RunLogger(value="编辑用户账号", isSaveRequest=true)
	@RequiresPermissions(value={"Account:modify"})
	@RequestMapping(value="/edit", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public MsgResult modify(Account entity){
		MsgResult msgRet = new MsgResult();
		try {
			getService().update(entity);
			msgRet.pushOk("修改成功!");
		} catch(Exception e) {
			msgRet.pushError("修改失败：" + e.getMessage());
			logger.error("修改时，发生异常！", e);
		}
		return msgRet;
	}

	@RunLogger(value="删除用户账号", isSaveRequest=true)
	@RequiresPermissions(value={"Account:remove"})
	@RequestMapping(value="/remove/{id}", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public MsgResult remove(@PathVariable("id") Long id){
		MsgResult msgRet = new MsgResult();
		try {
			getService().deleteById(id);
			msgRet.pushOk("删除成功！");
		} catch(Exception e) {
			msgRet.pushError("删除失败：" + e.getMessage());
			logger.error("删除时，发生异常！", e);
		}
		return msgRet;
	}

	@RunLogger(value="批量删除用户账号", isSaveRequest=true)
	@RequiresPermissions(value={"Account:remove"})
	@RequestMapping(value="/remove", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public MsgResult remove(@RequestParam("ids[]") Long[] ids){
		MsgResult msgRet = new MsgResult();
		try {
			getService().deleteByIds(ids);
			msgRet.pushOk("批量删除成功!");
		} catch(Exception e) {
			msgRet.pushError("批量删除失败：" + e.getMessage());
			logger.error("批量删除时，发生异常！", e);
		}
		return msgRet;
	}
	
	@RequiresPermissions(value={"Account:modify"})
	@RequestMapping(value="/modifyPassword", method={RequestMethod.GET})
	public ModelAndView modifyPassword(){
		ModelAndView mav = new ModelAndView(FORM_PWD_PAGE);
		return mav;
	}
	
	@RunLogger(value="修改账号密码", isSaveRequest=true)
	@RequiresPermissions(value={"Account:modify"})
	@RequestMapping(value="/modifyPassword", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public MsgResult modifyPassword(String plainPassword, String newPassword){
		MsgResult msgRet = new MsgResult();
		try {
			getService().updatePassword(getLoginUser().getId(), plainPassword, newPassword);
			msgRet.pushOk("修改密码成功!");
		} catch(Exception e) {
			msgRet.pushError("修改密码失败：" + e.getMessage());
			logger.error("修改密码时，发生异常！", e);
		}
		return msgRet;
	}
	
	@RunLogger(value="重置账号密码", isSaveRequest=true)
	@RequiresPermissions(value={"Account:reset"})
	@RequestMapping(value="/reset", method={RequestMethod.POST}, produces={ MediaType.APPLICATION_JSON_VALUE })
	@ResponseBody
	public MsgResult reset(Long id, String newPassword){
		MsgResult msgRet = new MsgResult();
		try {
			getService().resetPassword(id, newPassword);
			msgRet.pushOk("重置密码成功!");
		} catch(Exception e) {
			msgRet.pushError("重置密码失败：" + e.getMessage());
			logger.error("重置密码时，发生异常！", e);
		}
		return msgRet;
	}
}
